<template>
  <!-- 活动成绩 -->
  <div>
    <el-form class="pageWrap">
      <!-- <el-form-item label="报名日期" class="noBot"></el-form-item> -->
      <el-form-item label="活动组别" class="noBot">
        <span
          :class="['span',gId==v.id?'active':'']"
          v-for="(v,i) in groupArr"
          :key="i"
          @click="gId=v.id;getPlayers()"
        >{{v.name}}</span>
      </el-form-item>
      <el-form-item label="完赛状态" class="noBot">
        <span
          :class="['span',status==v.val?'active':'']"
          v-for="(v,i) in statusArr"
          :key="i"
          @click="status=v.val;getPlayers()"
        >{{v.name}}</span>
      </el-form-item>
    </el-form>
    <el-row class="pageWrap conmsg">
      <el-form :inline="true">
        <el-form-item class="noBot">
          <el-input v-model="name" placeholder="搜索选手姓名、手机号" @input="$forceUpdate()">
            <el-button slot="append" icon="el-icon-search" @click="getPlayers()"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item class="noBot">
          <el-button type="text" icon="el-icon-upload" @click="portTips">导出成绩表</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="gradeArr"
        style="width: 100%"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
        @sort-change="onSortChange"
        v-loading="tLoading"
      >
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="entryNumber" label="参赛号" sortable="custom"></el-table-column>
        <el-table-column prop="distance" label="距离" sortable="custom"></el-table-column>
        <el-table-column prop="sUseTime" label="用时" sortable="custom"></el-table-column>
        <el-table-column prop="goodCount">
          <template slot="header">
            <span>打卡次数</span>
            <el-tooltip effect="dark" content="有效打卡次数" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="runCount" label="运动次数" v-if="type=='J'">
          <template slot="header">
            <span>运动次数</span>
            <el-tooltip effect="dark" content="地图运动记录次数" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="lockCount" v-if="type=='J'">
          <template slot="header">
            <span>解锁数量</span>
            <el-tooltip effect="dark" content="打卡点解锁数量" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="sexRank" label="审核状态" width="80"></el-table-column> -->
        <el-table-column label="操作" align="center">
          <template slot-scope="{row}">
            <el-button type="text" circle @click="getRecord(row)">查看详情</el-button>
            <el-button type="text" circle v-if="status==0" @click="sureFinish(row)">完赛审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :hide-on-single-page="true"
        :current-page.sync="currP"
        :page-size="PageS"
        layout="prev, pager, next, jumper"
        :total="allNum"
        @current-change="getPlayers"
      ></el-pagination>
    </el-row>
    <el-dialog
      title="成绩信息"
      :visible.sync="seeDialog"
      width="80%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <p class="pand_tit">打卡记录</p>
      <table class="tabCard" style="width: 100%" v-loading="expandMsg.cardLoad">
        <tr>
          <th width="200">上传时间</th>
          <th>距离</th>
          <th>用时</th>
          <th>上升</th>
          <th>配速</th>
          <th class="viTit">
            <span :class="validORinvalid?'viact':''" @click="toggleVI(1,expandMsg)">有效</span>/
            <span :class="!validORinvalid?'viact':''" @click="toggleVI(2,expandMsg)">无效</span>
          </th>
          <th>截图</th>
          <th>操作</th>
        </tr>
        <tr v-for="v,i in expandMsg.cardCon.slice((dCP-1)*dPage,dCP*dPage)" :key="i">
          <td width="200">{{v.suppTime}}</td>
          <td>{{v.suppDistence}}</td>
          <td>{{v.suppUseTimeS}}</td>
          <td>{{v.suppUpDis}}</td>
          <td>{{v.suppPace}}</td>
          <td>
            <span v-if="!v.edit">{{v.state=='t'?'有效':v.state=='f'?'无效':v.state}}</span>
            <el-select
              v-model="v.state"
              @change="$forceUpdate();"
              v-else
              style="width:280px"
              filterable
              allow-create
            >
              <el-option label="有效" value="t"></el-option>
              <el-option label="无效" value="f"></el-option>
            </el-select>
          </td>
          <td>
            <img class="cardImg" :src="v.suppImgS[0]" v-showImgArr="{list:v.suppImgS,ind:0}" />
          </td>
          <td>
            <span class="recordeditBtn" v-if="!v.edit" @click="v.edit=true;$forceUpdate();">编辑</span>
            <span class="recordsaveBtn" v-else @click="saveRecord(v,expandMsg)">保存</span>
          </td>
        </tr>
        <tr v-if="expandMsg.cardCon.length==0">
          <td colspan="7">暂无</td>
        </tr>
      </table>
      <el-pagination
        :hide-on-single-page="true"
        :current-page.sync="dCP"
        :page-size="dPage"
        layout="prev, pager, next, jumper"
        :total="expandMsg.cardCon.length"
      ></el-pagination>
      <!-- 运动记录 活动轨迹记录 -->
      <div v-if="type=='J'">
        <p class="pand_tit">运动记录</p>
        <table class="tabCard" style="width: 100%">
          <tr>
            <th width="200">开始时间</th>
            <th width="200">结束时间</th>
            <th>距离</th>
            <th>用时</th>
            <th>配速</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
          <tr v-for="v,i in expandMsg.runRecord.slice((runCP-1)*runPage,runCP*runPage)" :key="i">
            <td width="200">{{v.creatTime}}</td>
            <td width="200">{{v.endTime}}</td>
            <td>{{v.distance}}</td>
            <td>{{v.ut}}</td>
            <td>{{v.runPace}}</td>
            <td>
              <span v-if="!v.edit">{{v.state=='t'?'有效':v.state=='f'?'无效':v.state}}</span>
              <el-select
                v-model="v.state"
                @change="$forceUpdate();"
                v-else
                style="width:280px"
                filterable
                allow-create
              >
                <el-option label="有效" value="t"></el-option>
                <el-option label="无效" value="f"></el-option>
              </el-select>
            </td>
            <td>
              <span class="recordeditBtn" v-if="!v.edit" @click="v.edit=true;$forceUpdate();">编辑</span>
              <span class="recordsaveBtn" v-else @click="saveRunState(v,expandMsg)">保存</span>
              <span class="seemapBtn" @click="seeRunPoy(v.id)">查看轨迹</span>
            </td>
          </tr>
          <tr v-if="expandMsg.runRecord.length==0">
            <td colspan="7">暂无</td>
          </tr>
        </table>
        <el-pagination
          :hide-on-single-page="true"
          :current-page.sync="runCP"
          :page-size="runPage"
          layout="prev, pager, next, jumper"
          :total="expandMsg.runRecord.length"
        ></el-pagination>
      </div>
    </el-dialog>
    <!-- 轨迹查看 -->
    <div class="mapBox" v-show="mapRunSee" v-loading="mapLoading" @click.self="mapRunSee=false">
      <div class="poyMap" id="Pmap"></div>
    </div>
  </div>
</template>

<script>
const formatSeconds = (a) => {
  var hh = parseInt(a / 3600);
  if (hh < 10) hh = "0" + hh;
  var mm = parseInt((a - hh * 3600) / 60);
  if (mm < 10) mm = "0" + mm;
  var ss = parseInt((a - hh * 3600) % 60);
  if (ss < 10) ss = "0" + ss;
  var length = hh + ":" + mm + ":" + ss;
  if (a > 0) {
    return length;
  } else {
    return "00:00:00";
  }
};
const forPace = (sp) => {
  // console.log(sp)
  if (!sp || sp == 0) {
    return "--'--\"";
  } else {
    // let aa = 60 / ((sp.toFixed(2) * 3.6).toFixed(2))
    let aa = sp.toFixed(2);
    let b = parseInt(aa);
    let c = parseInt((aa - parseInt(aa)) * 60);
    // console.log(aa,b,c)
    if (b < 10) b = "0" + b;
    if (c < 10) c = "0" + c;
    return b + "'" + c + '"';
  }
};
let getCenterAndZoom = (maxJ, minJ, maxW, minW, i) => {
  var centerLongitude = ((parseFloat(minJ) + parseFloat(maxJ)) / 2).toFixed(5);
  var centerLatitude = ((parseFloat(minW) + parseFloat(maxW)) / 2).toFixed(5);
  let zoom = getCenterPoint(maxJ, minJ, maxW, minW);
  if (i) {
    zoom += 1;
  }
  centerLongitude = Number(centerLongitude);
  centerLatitude = Number(centerLatitude);
  //如果经纬度在array中不是数字类型，需要转化为数字类型进行计算，如果是可以去掉parseFloat处理
  // console.log(centerLongitude,centerLatitude);
  return [centerLongitude, centerLatitude, zoom];
};
let getCenterPoint = (maxJ, minJ, maxW, minW) => {
  //通过经纬度获取中心位置和缩放级别
  let dd = getDistance(maxW, maxJ, minW, minJ);
  // console.log(dd)
  var diffArr = [
    0.01,
    0.02,
    0.05,
    0.05,
    0.1,
    0.2,
    0.5,
    1,
    2,
    5,
    10,
    20,
    50,
    50,
    100,
    200,
    500,
    1000,
  ];
  for (var i = 0; i < diffArr.length; i++) {
    if (diffArr[i] - dd > 0) {
      // 18 - i + 3
      return 19 - i + 3; //之所以会多4，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加4。
    }
  }
};
// 根据两点经纬度计算距离
const getDistance = (lat1, lng1, lat2, lng2) => {
  var radLat1 = (lat1 * Math.PI) / 180.0;
  var radLat2 = (lat2 * Math.PI) / 180.0;
  var a = radLat1 - radLat2;
  var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
  var s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    );
  s = s * 6378.137; // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000;
  return Number(s);
};
export default {
  data() {
    return {
      mapRunSee:false,
      mapLoading:false,
      tLoading: false,
      currP: 1,
      PageS: 10,
      allNum: 0,
      dCP: 1,
      dPage: 5,
      runCP: 1,
      runPage: 5,
      groupArr: [],
      gradeArr: [],
      name: "",
      gId: 0,
      expands: [],
      getRowKeys(row) {
        return row.id;
      },
      validORinvalid: true,
      type: "",
      sortV: 3, // 1距离；2，用时 3，参赛号
      sortBy: 2, // 1正序；2，倒序,
      expandMsg: { cardLoad: false, cardCon: [], runRecord: [] },
      seeDialog: false,
      statusArr:[{val:1,name:'已审核完成'},{val:0,name:'未审核完成'}],
      status:1
    };
  },
  methods: {
    onSortChange(val) {
      if (val.prop == "distance") {
        this.sortV = 1;
      } else if (val.prop == "sUseTime") {
        this.sortV = 2;
      } else if ((val.prop = "entryNumber")) this.sortV = 3;
      if (val.order == "ascending") this.sortBy = 1;
      else this.sortBy = 2;
      this.getPlayers();
    },

    // 获取赛项
    getGroupArr() {
      this.$axios
        .get("/sbr/match/getMatchInfos/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          let rr = res.data.data;
          this.gId = rr.matchInfoLists[0].id;
          this.groupArr = rr.matchInfoLists;
          this.type = rr.type;
          this.getPlayers();
        });
    },
    getPlayers() {
      let oo = {
        matchId: this.$Base64.decode(sessionStorage.getItem("MandA")),
        groupId: this.gId,
        name: this.name,
        type: this.sortV, // 1距离；2，用时
        sort: this.sortBy, // 1正序；2，倒序,
        page: this.currP,
        status:this.status
      };
      this.gradeArr = [];
      this.tLoading = true;
      this.$axios
        .get("/sbr/match/getPersonMatchList", { params: oo })
        .then((res) => {
          let rr = res.data.data;
          this.allNum = rr.num;
          rr.list.forEach((v) => {
            v.sUseTime = formatSeconds(v.useTime);
          });
          this.tLoading = false;
          this.gradeArr = rr.list;
        });
    },
    // 确认完成
    sureFinish(row){
      this.$confirm('确认该选手已完赛，确认后该选手再次提交的数据将不计入有效成绩中', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let o={id:row.id,status:1}
          this.$axios.get('/sbr/match/getPersonMatchStatus',{params:o}).then(res=>{
            this.getPlayers()
          this.$message({
            type: 'success',
            message: '已确认完赛!'
          });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
    },
    // 展开行 查看打卡详情
    zydescription(dd, expandedRows) {
      // console.log(dd);
      var that = this;
      if (expandedRows.length) {
        that.expands = [];
        if (dd) {
          that.expands.push(dd.id);
          that.expandMsg = { cardLoad: false, cardCon: [], runRecord: [] };
          this.getRecord(dd);
        }
      } else {
        that.expands = [];
      }
    },
    // 获取打卡 / 运动 记录
    getRecord(dd) {
      let that = this;
      that.expandMsg = { cardLoad: false, cardCon: [], runRecord: [] };
      this.seeDialog = true;
      // dd.cardLoad = true;
      // dd.cardCon = [];
      // dd.runRecord = [];
      this.expandMsg.cardLoad = true;
      this.expandMsg.cardCon = [];
      this.expandMsg.runRecord = [];
      this.expandMsg.matchId = dd.matchId;
      this.expandMsg.groupId = dd.groupId;
      this.expandMsg.openId = dd.openId;
      let o = {
        matchId: dd.matchId,
        groupId: this.gId,
        openId: dd.openId,
      };
      this.$axios
        .get("/sbr/person/match/getPersonMatchDataSupp", { params: o })
        .then((res) => {
          let rr = res.data.data;
          // this.expandMsg.cardLoad = false;
          this.$set(this.expandMsg, "cardLoad", false);
          rr.forEach((v) => {
            v.suppUseTimeS = formatSeconds(v.suppUseTime);
            v.suppImgS = v.suppImg.split(";");
            v.edit = false;
          });
          this.expandMsg.cardCon = rr;
          // 无效
          this.expandMsg.invalid = rr.filter((v) => {
            return v.state != "t";
          });
          // 有效
          this.expandMsg.valid = rr.filter((v) => {
            return v.state == "t";
          });
          if (this.validORinvalid)
            this.expandMsg.cardCon = this.expandMsg.valid;
          else this.expandMsg.cardCon = this.expandMsg.invalid;
          // console.log(this.expandMsg);
          // 获取运动记录
          if (this.type == "J") {
            this.$axios
              .get("/sbr/run/getPersonMatchDateByOpenId", { params: o })
              .then((res) => {
                let rr = res.data.data;
                this.expandMsg.cardLoad = false;
                rr.forEach((v) => {
                  v.ut = formatSeconds(v.useTime);
                  if (v.distance > 0) {
                    v.runPace = forPace(v.useTime / 60 / v.distance);
                  } else {
                    v.runPace = "0'0''";
                  }
                  v.edit = false;
                });
                this.expandMsg.runRecord = rr;
                this.$forceUpdate();
              });
          }
          this.$forceUpdate();
        });
    },
    // 切换有效无效
    toggleVI(i, row) {
      if (i == 1) {
        row.cardCon = row.valid;
        this.validORinvalid = true;
      } else {
        row.cardCon = row.invalid;
        this.validORinvalid = false;
      }
      this.dCP = 1;
      this.$forceUpdate();
    },
    // 打卡记录状态修改
    saveRecord(v, bigRow) {
      // console.log(v.state);
      this.$axios.post("/match/putPersonMatchData", v).then((res) => {
        v.edit = false;
        this.getThisPer(bigRow);
        this.$message.success("修改成功");
        this.$forceUpdate();
      });
    },
    // 查询单条记录
    getThisPer(bigRow) {
      let o = {
        matchId: bigRow.matchId,
        groupId: bigRow.groupId,
        openId: bigRow.openId,
      };
      this.$axios
        .get("/sbr/match/getPersonMatchByOpenId", { params: o })
        .then((res) => {
          let rr = res.data.data;
          if (rr) {
            let i = this.gradeArr.findIndex((v) => {
              return v.id == rr.id;
            });
            rr.sUseTime = formatSeconds(rr.useTime);
            if (i >= 0) {
              // this.gradeArr[i] = JSON.parse(JSON.stringify(rr));
              this.gradeArr.splice(i, 1, rr);
            }
            this.$forceUpdate();
            this.getRecord(rr);
          }
        });
    },
    // 导出提示
    portTips() {
      this.$confirm("确认导出？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.portData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    portData() {
      console.log(1);
      let o = {
        groupId: this.gId,
        name:
          this.groupArr.find((v) => {
            return v.id == this.gId;
          }).name + "成绩表",
      };
      // this.$axios({
      //   url: "/sbr/match/portPersonMatchList",
      //   method: "get",
      //   headers: {
      //     "Content-Type": "multipart/form-data",
      //   },
      //   params:o,
      //   // data:o,
      //   responseType: "blob",
      // }).then((res) => {
      //   let rr = res.data.data;
      // });
      let link = document.createElement("a");
      // let blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); //生成blob对象
      // console.log(blob);
      link.style.display = "none";
      // link.href = URL.createObjectURL(blob);
      link.href =
        this.$url +
        `/sbr/match/portPersonMatchList?groupId=${o.groupId}&name=${o.name}`;
      // link.setAttribute("download", "冲突设备" + ".xls"); //下载的文件名以及文件格式
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 运动记录状态保存
    saveRunState(v, row) {
      // /sbr/run/putRunDataState
      let o = {
        id: v.id,
        state: v.state,
      };
      console.log(o);
      this.$axios.get("/sbr/run/putRunDataState", { params: o }).then((res) => {
        v.edit = false;
        this.getThisPer(row);
        this.$message.success("修改成功");
        this.$forceUpdate();
      });
    },
    seeRunPoy(id) {
      // poyMap
      this.mapRunSee=true
      var map = new qq.maps.Map(document.getElementById("Pmap"), {
        center: new qq.maps.LatLng(39.916527, 116.397128), // 地图的中心地理坐标。
        zoom: 8, // 地图的中心地理坐标。
      });
      this.mapLoading=true
      // id 1856
      this.$axios.get("/sbr/run/getPersonRunDataById?id="+id).then((res) => {
        let rr = res.data.data;
        if (rr.list && rr.list.length > 0) {
          let pp = rr.list.map((v) => {
            return {
              latitude: v.lat,
              longitude: v.lng,
            };
          });

          let lngArr = pp.map((v) => {
            return v.longitude;
          });
          let latArr = pp.map((v) => {
            return v.latitude;
          });
          let maxlng = Math.max(...lngArr);
          let minlng = Math.min(...lngArr);
          let maxlat = Math.max(...latArr);
          let minlat = Math.min(...latArr);
          let centerD = getCenterAndZoom(maxlng, minlng, maxlat, minlat);
          var map = new qq.maps.Map(document.getElementById("Pmap"), {
            center: new qq.maps.LatLng(centerD[1], centerD[0]), // 地图的中心地理坐标。
            zoom: centerD[2], // 地图的中心地理坐标。
          });
          console.log(pp[0])
          var path = pp.map((v) => {
            return new qq.maps.LatLng(v.latitude, v.longitude);
          });
           new qq.maps.Polyline({
            map: map,
            path: path,
            strokeColor: "#ff0000",
            StrokeWeight: 6,
          });
        } else {
          this.$message.warning("运动轨迹为空");
        }
      this.mapLoading=false
      });
    },
  },
  created() {
    this.getGroupArr();
  },
  mounted() {
    // this.initMap();
  },
};
</script>
<style scoped>
/* @import url(); 引入公共css类 */
/* .pageWrap >>> .el-table__expand-column {
  display: none;
} */
.noBot {
  margin-bottom: 0;
}
.conmsg {
  margin-top: 15px;
}
.span {
  padding: 0 12px;
  line-height: 25px;
  display: inline-block;
  cursor: pointer;
  margin-right: 6px;
  margin-top: 10px;
  overflow: hidden;
  border: 1px solid transparent;
}
.span.active {
  border-color: #409eff;
  border-radius: 12px;
  color: #409eff;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.tabCard th,
.tabCard td {
  text-align: center;
  line-height: 40px;
}
.cardImg {
  width: 100px;
  height: 100px;
}
.viTit {
  cursor: pointer;
}
.viact {
  color: #409eff;
}
.pand_tit {
  margin: 10px;
  font-weight: 500;
  font-size: 18px;
}
.recordeditBtn,
.recordsaveBtn {
  cursor: pointer;
  color: #409eff;
}
.recordsaveBtn {
  color: #67c23a;
}
.seemapBtn{
  cursor: pointer;
  color: #409eff;
  margin-left: 10px;
}
.mapBox {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 8888;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.poyMap {
  width: 80%;
  height: 80%;
  background-color: #fff;
}
</style>